import Vue from 'vue'
import Loading from './loading.vue'
import pageScroll from '../../../_common/js/utils/pageScroll'
let instancesObj = {}
Loading.new = (options = {}) => {
  // options identify
  if (options.identify && instancesObj[options.identify]) {
    let opr = instancesObj[options.identify]
    ++opr.$extraCounter
    return opr
  }
  const instance = new Vue({
    data: options,
    render (h) {
      return h(Loading, {
        props: options
      })
    }
  })
  const component = instance.$mount()
  document.body.appendChild(component.$el)
  pageScroll.lock(component.$el)

  const loading = instance.$children[0]
  const opr = {
    $extraCounter: 0,
    close () {
      if (opr.$extraCounter) {
        --opr.$extraCounter
      } else {
        opr.forceClose()
      }
    },
    forceClose () {
      opr.$extraCounter = 0
      const el = loading.$el
      pageScroll.unlock(el)
      el.parentNode && el.parentNode.removeChild(el)
      typeof loading.callback === 'function' && loading.callback()
      if (options.identify) {
        instancesObj[options.identify] = null
      }
    }
  }
  // options identify
  if (options.identify) {
    instancesObj[options.identify] = opr
  }
  return opr
}

Loading.newWithPromise = (promise, options) => {
  return new Promise((resolve, reject) => {
    let loading = Loading.new(options)
    promise.then(result => {
      loading.close()
      resolve(result)
    }).catch(err => {
      loading.close()
      reject(err)
    })
  })
}

Loading.getWithIdentify = function (identify) {
  return instancesObj[identify]
}
export default Loading
